﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using XZTZ.UMP.Public.Models.Base;
using XZTZ.UMP.WEB.Data;

namespace XZTZ.UMP.WEB.Pages.Base.CompanyInfo
{
    public class EditModel : PageModel
    {
        private readonly XZTZ.UMP.WEB.Data.ApplicationDbContext _context;

        public EditModel(XZTZ.UMP.WEB.Data.ApplicationDbContext context)
        {
            _context = context;
        }

        [BindProperty]
        public XZTZ.UMP.Public.Models.Base.CompanyInfo CompanyInfo { get; set; }

        public async Task<IActionResult> OnGetAsync(Guid? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            CompanyInfo = await _context.CompanyInfo
                .Include(c => c.CompanyType).FirstOrDefaultAsync(m => m.guidCompanyID == id);

            if (CompanyInfo == null)
            {
                return NotFound();
            }
           ViewData["guidCompanyTypeID"] = new SelectList(_context.CompanyType, "guidCompanyTypeID", "strTypeName");
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Attach(CompanyInfo).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CompanyInfoExists(CompanyInfo.guidCompanyID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return RedirectToPage("./Index");
        }

        private bool CompanyInfoExists(Guid id)
        {
            return _context.CompanyInfo.Any(e => e.guidCompanyID == id);
        }
    }
}
